import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { ToolRegistry, ToolManager } from '../../Tool';
import registerCesiumAppTool from './Tools/index';
import VGE from '../../VGE';
import { Camera } from './Camera';
import { Misc } from './Misc';
import { Layer } from './Layer';
import { Marker } from './Marker';
import { Polyline } from './Polyline';
import { Polygon } from './Polygon';

export default class MapApp {
	static async open(sceneData = {}, callback) {
		try {
			const {
				sceneUrl,
				container,
				cameraParams = {},
				homeView = {},
				token,
				loadOptions = {}
			} = sceneData;

			const dom = await VGE.util.findOrCreateDom(container);

			mapboxgl.accessToken = token;
			const options = Object.assign(
				{ style: sceneUrl, container: dom, preserveDrawingBuffer: true },
				loadOptions
			);
			window.rxMap = this.viewer = new mapboxgl.Map(options);

			this.homeViewParams = homeView;

			this.viewer?.resize();
			try {
				callback && callback(this.viewer);
			} catch (e) {
				console.log(e);
			}

			this.camera = new Camera(this.viewer);
			this.misc = new Misc(this.viewer);
			this.layer = new Layer(this.viewer);
			this.marker = new Marker(this.viewer);
			this.polyline = new Polyline(this.viewer);
			this.polygon = new Polygon(this.viewer);

			// 同步前场景相机参数
			this.camera.flyTo(cameraParams);

			this.viewer._controlContainer?.remove();
			this.viewer._canvas.style.background =
				'linear-gradient(to bottom, #72a1e2 0%, #fff 44%, #f1f1f1)';

			setTimeout(() => {
				registerCesiumAppTool();
			});

			return this.viewer;
		} catch (e) {
			console.error(e.message);
		}
	}

	static async close() {
		if (this.viewer) {
			this.viewer.remove();
			this.viewer._canvas.style.background = '';
			this.viewer._container.innerHTML = '';
		}
	}
}
MapApp.viewer = null;
MapApp.tools = new ToolRegistry();
MapApp.toolManager = new ToolManager();
MapApp.homeViewParams = {};
MapApp.camera = null;
MapApp.misc = null;
MapApp.layer = null;
MapApp.marker = null;
MapApp.polyline = null;
MapApp.polygon = null;
